登录 白背景

2078. 两栋颜色不同且距离最远的房子

https://leetcode-cn.com/problems/two-furthest-houses-with-different-colors/

  • 提交时间:2021-11-23 17:39:46
  • 执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户
  • 内存消耗:2.3 MB, 在所有 Go 提交中击败了5.06%的用户
  • 通过测试用例:126 / 126
func maxDistance(colors []int) (ans int) {
    earlyMap := map[int]int{}
    lastMap := map[int]int{}
    for index, col := range colors {
        if _, ok := earlyMap[col]; !ok {
            earlyMap[col] = index
        }
        if item, ok := lastMap[col]; !ok || item < index {
            lastMap[col] = index
        }
    }
    // fmt.Printf("earlyMap:%+v\n", earlyMap)
    // fmt.Printf("lastMap:%+v\n", lastMap)
    for col, pos := range earlyMap {
        for col2, pos2 := range lastMap {
            if col == col2 {
                continue
            }
            // fmt.Printf("abs(pos-pos2):%+v\n", abs(pos-pos2))
            ans = max(ans, abs(pos-pos2))
        }
    }
    return ans
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

func max(x, y int) int {
    if x > y {
        return x
    }
    return y
}